<?php

class Application_Model_wayBillItem extends Application_Model_DomainObject implements Application_Model_PayInterface {

// `discountFee`, `serviceFee`, `shipFee`, `status`, `useScore`, `userId`, `noSkin`, `shipType`, `shipFeeconfig`, `shipMoney`, `consignee`, `conAdd`, `conTel`, `conPostCode`, `bagWeight`, `weight`, `logistics`, `comment`
    protected $_id; //序号
    protected $_billNo; //UUCH内部运单号
    protected $_dateCreated; //创建日期
    protected $_dateSend; //发货日期
    protected $_dateUserConfrim; //用户确认收货日期
    protected $_datePaid; //付款日期
    protected $_stockDate;//结算时间
    protected $_lastdate; //最后更新时间------
    protected $_status; //前台状态 0:等待付款 1：受理中(正在发货) 2:已经发货 100：已经完成 -1:取消 -2:海关退货；
    protected $_userId; //用户ID
    protected $_weight; //结算重量
    protected $_bagWeight; //包裹重量
    protected $_volumeWeight; //体积重量--------
    protected $_productWeight; //物品总重量-------
    protected $_lastWeight; //最终重量-----------
    protected $_isVolume; //是否收了体积重量XXX
    protected $_expressId; //运送方式
    protected $_shipType; //运送方式 从Express里面取值
    protected $_shipFeeconfig; //运送方式  从ExpressPrice里面取值
    protected $_state; //国家--------
    protected $_consignee; //收货人
    protected $_conAdd; //收货人地址
    protected $_conTel; //收货人电话
    protected $_conPostCode; //收货人邮编            
    protected $_isNoLogo; //是否去掉吊牌，Logo等------
    protected $_isNoSkin; //是否要去掉不必要包装---------
    protected $_isCompress; //是否要压缩抽气----------
    protected $_discountFee; //折扣金额
    protected $_serviceFee; //服务费
    protected $_shipFee; //邮费
    protected $_shipMoney; //预收总运费   
    protected $_reportFee; //报关费---------
    protected $_lastMoney; //最终收款----------
    protected $_costMoney; //成本价----------    
    protected $_useScore; //使用积分
    protected $_logistics; //物流单号
    protected $_agentId; //货代公司
    protected $_agentNo; //代理公司单号
    protected $_comment; //评论序号
    protected $_refundMoney;  //订单退款
    protected $_lastVolumeWeight; //最终体积重量
    protected $_expressCostId; //快递成本ID，用于标记快递走了哪一个通道，用了多少成本
    protected $_channer; //渠道
    protected $_remark; //备注
    protected $_lwhth; //长宽高
    protected $_fee; //住宅费
    protected $_interior; //内部状态
    protected $_problem; //问题状态
    protected $_isWooden; //木架加固
    protected $_paymentWeight; //预付重量
    protected $_isInvoice; //是否已出发票
    protected $_isAddform; //是否已打印地址标签
    protected $_dutyNo; //税号
    protected $_interiorRemark; //内部备注

    /**
     *  等待付款
     */

    const STATUS_WaitPay = 0;

    /**
     * 等待受理
     */
    const STATUS_Processing = 1;

    /**
     * 已经发货
     */
    const STATUS_Sended = 2;

    /**
     * 已受理
     */
    const STATUS_Confrimed = 3;

    /**
     * 已经完成
     */
    const STATUS_Complated = 100;

    /**
     * 取消
     */
    const STATUS_Cancel = -1;

    /**
     * 海关退货
     */
    const STATUS_Back = -2;

    /**
     * 快递拒收 
     */
    const STATUS_NoAppect = -3;

    /**
     * 快递退包 
     */
    const STATUS_ExpressBack = -4;

    /**
     * 未启用
     */
    const STATUS_Launch = -5;

    /**
     * 未付款
     */
    const Interior_WaitPay = 0;

    /**
     * 待受理
     */
    const Interior_Processing = 1;

    /**
     * 已受理待选择渠道
     */
    const Interior_Confrimed = 2;

    /**
     * 已选择渠道待拣货
     */
    const Interior_Incoice = 3;

    /**
     * 已拣货待打包
     */
    const Interior_Picking = 4;

    /**
     * 拣货异常
     */
    const Interior_PickError = 20;

    /**
     * 已打包待确认渠道
     */
    const Interior_Pick = 5;

    /**
     * 已确认渠道待交运
     */
    const Interior_AffirmChannel = 6;

    /**
     * 已交运待上系统
     */
    const Interior_Outstorage = 10;

    /**
     * 已上系统
     */
    const Interior_System = 11;

    /**
     * 上系统超期
     */
    const Interior_OverSystem = 21;

    /**
     * 已出转单
     */
    const Interior_Singleno = 12;

    /**
     * 出转单超期
     */
    const Interior_Oversingleno = 22;

    /**
     * 已上网
     */
    const Interior_Transportation = 13;

    /**
     * 上网超期
     */
    const Interior_OutTransportation = 23;

    /**
     * 完成超期
     */
    const Interior_Overachieve = 24;

    /**
     * 已完成
     */
    const Interior_Achieve = 100;

    /**
     * 未启用
     */
    const Interior_Launch = -5;

    /**
     * 已取消
     */
    const Interior_Cancel = -1;

    /**
     * 默认无错
     */
    const Problem_default = 0;

    /**
     * 出现问题
     */
    const Problem_Appear = 1;

    /**
     * 解决问题
     */
    const Problem_Aolve = 2;

    /**
     * 运单取消
     */
    const Problem_Cancel = 3;

    /**
     * 状态枚举
     * @return array 
     */
    public static function getStatusEnum() {
        return array(0 => '等待付款', 1 => '等待受理', 2 => '已经发货', 3 => '已经受理', 100 => '已经完成', -1 => '取消', -2 => '海关退货', -3 => '快递拒收', -4 => '出现问题', '-5' => '未启用');
    }

    public function getProblemType() {
        switch ($this->_problem) {
            case self::Problem_default:
                return "正常";
                break;
            case self::Problem_Appear:
                return "出现问题";
                break;
            case self::Problem_Aolve:
                return "问题解决";
                break;
            case self::Problem_Cancel:
                return "运单取消";
                break;
        }
    }

    /**
     * 设置运单重量
     * @param type $weight 结算重量
     * @param type $bagWeight 包裹重量
     * @param type $productWeight 物品总重量
     * @param type $volumWeight 物品体积重量
     */
    public function setAllWeight($weight, $bagWeight, $productWeight, $volumeWeight) {
        $this->_weight = $weight;
        $this->_bagWeight = $bagWeight;
        $this->_productWeight = $productWeight;
        $this->_volumeWeight = $volumeWeight;
    }

    /**
     * 设置收货地址
     * @param Application_Model_address $address 
     */
    public function setAddress($address) {
        $this->_state = $address->State;
        $this->_consignee = $address->LinkMan; //收货人
        $this->_conAdd = $address->Street; //收货人地址
        $this->_conTel = $address->Mobile; //收货人电话
        $this->_conPostCode = $address->Postcode; //收货人邮编            
    }

    /**
     * 设置运单金额
     * @param type $shipMoney 预收总运费
     * @param type $shipFee 邮费
     * @param type $reportFee 报关货
     * @param type $discountFee 折扣金额
     * @param type $serviceFee 服务费
     */
    public function setAllMoney($shipMoney, $shipFee, $reportFee, $discountFee, $serviceFee) {
        $this->_shipMoney = $shipMoney;
        $this->_shipFee = $shipFee;
        $this->_reportFee = $reportFee;
        $this->_serviceFee = $serviceFee;
        $this->_discountFee = $discountFee;
    }

    private $_logisticsItems; //运单物流信息

    /*
     * 获取当前运单物流信息
     */

    public function logisticsItems() {
        if (!empty($this->_logisticsItems)) {
            return $this->_logisticsItems;
        } else {

            if ($this->_logistics) {
                $this->_logisticsItems = Application_Model_logisticslogItem::getByNo($this->_logistics);
                return $this->_logisticsItems;
            } else {
                return null;
            }
        }
    }

    public function getLogisticsItems() {
        if (!$this->_logisticsItems) {
            $this->_logisticsItems = Application_Model_logisticslogItem::getByWayId($this->_id);
        }
        return $this->_logisticsItems;
    }

    private $_storeItems;

    /*
     * 仓库信息
     */

    public function getStoreItems() {
        if (empty($this->_storeItems)) {
            if (count($this->getItems()) == 0) {
                $this->_storeItems = Application_Model_StoreItem::getBywayId($this->Id);
            } else {
                $this->_storeItems = Uuch_Util::select($this->getItems(), function($item) {
                            return Application_Model_StoreItem::load($item->StoreItemId);
                        });
            }
        }
        $result = array();
        foreach ($this->_storeItems as $v) {
            $result[$v->Id] = $v->LocationNo;
        }
        asort($result);
        $items = array();
        foreach ($result as $k => $val) {
            $items[] = Application_Model_StoreItem::load($k);
        }
        return $items;
    }

    private $_agent;

    public function getAgentBy() {
        if ($this->_agent == NULL)
            $this->_agent = Application_Model_AgentCompany::load($this->_agentId);
        return $this->_agent;
    }

    /**
     * 返回运单当前状态
     * @return type 
     */
    public function getStatusName() {
        $names = Application_Model_wayBillItem::getStatusEnum();
        return $names[$this->_status];
    }

    public function statusname() {

        switch ($this->_status) {
            case 0:
                return "等待付款";
                break;
            case 1:
                return "正在发货";
                break;
            case 2:
                return "已经发货";
                break;
            case 100:
                return "已经完成";
                break;
            case -1:
                return "已经撤消";
                break;
            case -2:
                return "海关退货";
                break;
        }

        //状态 0:等待付款 1：受理中(正在发货) 2:已经发货 100：已经完成 -1:取消 -2:海关退货；
    }

    /*
     * 获取用户名
     */

    public function username() {
        $user = Application_Model_User::load($this->_userId);

        return $user->nikename;
    }

    /*
     * 返回数据持久化对象
     * @return Application_Model_StoreItem
     */

    protected static function getDb() {
        return new Application_Model_DbTable_wayBillItem();
    }

    /*
     * 根据userid返回一个数组
     * @param int $userid
     * @return array
     */

    public static function getByuserId($userid, $state, $start, $row) {

        $result = Application_Model_wayBillItem::getDb()->getByUser($userid, $state, $start, $row); //

        /* foreach ($result as $item){
          if($item->id!=null)
          {
          $item->product = new Application_Model_Product($item->id);
          }
          } */

        return $result;
    }

    /*
     * 根据用户名，状态获取当前记录总数
     * @param int $userid 用户序号
     * @param int $state 用户序号
     * @return int
     */

    public static function getItemCount($userid, $state) {
        if ($state == -1) {
            $where["status != "] = Application_Model_wayBillItem::STATUS_Cancel;
            $where[" and status != "] = Application_Model_wayBillItem::STATUS_Complated;
            $where[" and userId = "] = $userid;
            return self::getDao()->count($where);
        } else {
            $bill = new Application_Model_DbTable_wayBillItem();
            return $bill->getItemCount($userid, $state);
        }
    }

    /**
     * 确认收货
     */
    public static function sign($id) {
        if ($id > 0) {
            $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
            $db = $bootstrap->getResource('db');
            $set = array(
                'status' => 100,
                'dateUserConfrim' => date('Y-m-d H:i:s'),
            );
            $where = $db->quoteInto('id = ?', $id);
            $rows_affected = $db->update('uuch_waybill', $set, $where);

            if ($rows_affected > 0) {
//                $getItem = new Application_Model_wayBillItem($id);
//                    //更新物流信息
//                    $newitem=new Application_Model_logisticslogItem();
//                    $newitem->logisticsNo=$getItem->logistics;//物流单号
//                    $newitem->opDate=date('Y-m-d H:i:s');//操作时间
//                    $newitem->opRemark=$getItem->conAdd;//操作描述
//                    $newitem->opState="用户确认收货";//操作状态
//                    $newitem->opUser=$getItem->userId;;//操作者
//                    $newitem->save();
                return true;
            }

            return false;
        }

        return false;
    }

    /**
     * 根据指定的条件返回运单
     * @param int $wayid
     * @param int $memberId
     * @param date $startTime 开始时间
     * @param date $endTime 结束时间
     * @param int $status 订单状态
     * @param int $count
     * @param int $offset
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($wayid, $memberId, $startTime, $endTime, $status, $count, $offset) {
        $where = array();
        $and = '';
        if ($wayid != NULL) {
            $where['Id = '] = $wayid;
            $and = ' and ';
        }

        if ($memberId != NULL) {
            $where[$and . ' userId = '] = $memberId;
            $and = ' and ';
        }

        if ($startTime != NULL) {
            $where[$and . ' dateCreated >= '] = $startTime;
            $and = ' and ';
        }

        if ($endTime != NULL) {
            $where[$and . ' dateCreated <= '] = $endTime;
            $and = ' and ';
        }

        if ($status != NULL) {
            $where[$and . ' status = '] = $status;
            $and = ' and ';
        }

        return Application_Model_wayBillItem::getDb()->queryPage($where, 'dateCreated desc', $count, $offset);
    }

    public function getMoney() {
        return $this->ShipMoney;
    }

    public function getPayName() {
        return '悠奇-国际运单';
    }

    public function getPayCommen() {
        return "国际运单流水号：" . $this->_billNo;
    }

    public function isRepeatPay() {
        if ($this->_status == self::STATUS_WaitPay) {
            return true;
        }
        return false;
    }

    public function setPaid() {
        $this->_status = Application_Model_wayBillItem::STATUS_Processing;
        $this->_interior = self::Interior_Processing;
        $this->_datePaid = date('Y-m-d H:i:s');
    }

    public function canPay($userId) {
        if ($this->_userId != $userId)
            return FALSE;

        if ($this->_status != Application_Model_wayBillItem::STATUS_WaitPay)
            return FALSE;

        return TRUE;
    }

    public function getShipName() {
        return $this->getShipTypeBy()->Name;
    }

    private $shipBy;

    /**
     * 返回对应的快递公司 ,ShipType表与Express表ID一样，如要取物流信息，需要从ShipType取数据
     */
    public function getShipTypeBy() {
        if (!isset($this->shipBy)) {
            $this->shipBy = Application_Model_shipType::load($this->_shipType);
        }
        return $this->shipBy;
    }

    private $express;

    /**
     * 
     * @return Application_Model_Express
     */
    public function getExpressBy() {
        $sureExpressId = $this->_expressId ? $this->_expressId : $this->_shipType;
        if ($this->express == NULL) {
            $this->express = Application_Model_Express::load($sureExpressId);
        }
        return $this->express;
    }

    private $sureExpress;

    /**
     * @return Application_Model_Express
     */
    public function getExpressChannelBy() {
        $sureExpressId = $this->_channer ? $this->_channer : $this->_expressId;
        $channel = Application_Model_WayLog::getByWayIdInteriorType($this->_id, Application_Model_WayLog::Type_BillAffirmChannel);
        $sureShipType = $channel ? $channel->Description : $sureExpressId;
        if ($this->sureExpress == NULL) {
            if ($channel || $this->_channer) {
                $item = Application_Model_ExpressChannel::load($sureShipType);
                if ($item) {
                    $this->sureExpress = Application_Model_Express::load($item->ExpressId);
                } else {
                    $this->sureExpress = Application_Model_Express::load($this->_expressId);
                }
            } else {
                $this->sureExpress = Application_Model_Express::load($this->_expressId);
            }
        }
        return $this->sureExpress;
    }

    public function getBillNo() {
        return $this->_billNo;
    }

    public function getPayDescription() {
        return '支付悠奇国际运单费用，用户名:' . Application_Model_User::load($this->_userId)->Email;
    }

    private $_cityBy = null;

    public function getCityBy() {
        if ($this->_cityBy == NULL)
            $this->_cityBy = Application_Model_city::load($this->_state);
        return $this->_cityBy;
    }

    /**
     * 取消运单 
     */
    public function cancelWay() {
        try {
            $this->getDbTable()->beginTran();

            foreach ($this->getStoreItems() as $item) {
                $item->WayId = NULL;
                $item->State = Application_Model_StoreItem::STATUS_InStored;
                $item->save();
            }

            $coupons = Application_Model_Coupon::getByWayId($this->id);
            foreach ($coupons as $coupon) {
                $coupon->Relevance = null;
                $coupon->Status = Application_Model_Coupon::STATUS_OK;
                $coupon->save();
            }

            if ($this->_status == Application_Model_wayBillItem::STATUS_Processing) {
                $account = Application_Model_UserAccount::load($this->_userId);

                $history = new Application_Model_UserAccountHistory();
                $history->Type = Application_Model_UserAccountHistory::TYPE_RECHARGE_MONEY;
                $history->BeforeMoney = $account->Money;
                $history->AfterMoney = $account->Money + $this->_shipMoney;
                $history->Comment = '取消运单(' . $this->_billNo . ')退款';
                $history->DateCreated = date('Y-m-d H:i:s');
                $history->RelaseId = $this->_id;
                $history->BeforeScore = $account->Score;
                $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
                $history->AfterScore = $account->Score;
                $history->AccountId = $account->Id;
                $history->save();

                $account->Money += $this->getFeeByType(Application_Model_FeeType::EstimateSum);
                $account->save();
            }
            $this->_status = Application_Model_wayBillItem::STATUS_Cancel;
            $this->_interior = self::Interior_Cancel;
            $this->save();
            $this->getDbTable()->commit();
        } catch (Exception $ex) {
            $this->getDbTable()->rollBack();
            throw $ex;
        }
    }

    private $_items;

    /**
     * 返回运单中所有的货物
     */
    public function getItems() {
        if ($this->_items == NULL) {
            $this->_items = Application_Model_WayItem::getByWayId($this->_id);
        }
        return $this->_items;
    }

    /**
     * 往运单里面添加货物
     * @param type $storeItem
     */
    public function addItem($storeItemId) {
        $items = $this->getItems();
        $newItem = new Application_Model_WayItem();
        $newItem->WayId = $this->_id;
        $newItem->StoreItemId = $storeItemId;
        $newItem->Status = 0;
        $newItem->save();
        $items[] = $newItem;
    }

    private $_fees;

    /**
     * 返回运单的费用明细
     */
    public function getFees() {
        if ($this->_fees == NULL) {
            $this->_fees = Application_Model_WayFee::getByWayId($this->_id);
        }
        return $this->_fees;
    }

    /**
     * 跟据类型返回服务费用
     * @param int $feeType
     * @return int
     */
    public function getFeeByType($feeType) {
        $fee = Uuch_Util::first($this->getFees(), function($item) use($feeType) {
                    return $item->FeeType == $feeType;
                });
        if ($fee) {
            return $fee->Money;
        } else {
            switch ($feeType) {
                case Application_Model_FeeType::CouponFee:
                    return $this->_discountFee;
                case Application_Model_FeeType::EstimateShipFee:
                    return $this->_shipFee;
                case Application_Model_FeeType::EstimateSum:
                    return $this->_shipMoney;
                case Application_Model_FeeType::LastSum:
                    return $this->_lastMoney;
                case Application_Model_FeeType::StoreServiceFee:
                    return $this->_serviceFee;
                case Application_Model_FeeType::ReportFee:
                    return $this->_reportFee;
                case Application_Model_FeeType::CostFee:
                    return $this->_costMoney;
                case Application_Model_FeeType::RefoundFee:
                    return $this->_refundMoney;
            }
            return 0;
        }
    }

    /**
     * 添加一个费用
     */
    public function addFee($feeType, $money) {
        $fees = $this->getFees();
        $fee = new Application_Model_WayFee();
        $fee->FeeType = $feeType;
        $fee->Money = $money;
        $fee->WayId = $this->_id;
        $fee->save();
        $fees [] = $fee;
    }

    public function addOrNewFee($feeType, $money) {
        $feeItem = Application_Model_WayFee::getByWayIdFeeType($this->_id, $feeType);
        if (!$feeItem) {
            $feeItem = new Application_Model_WayFee();
        }
        $feeItem->FeeType = $feeType;
        $feeItem->Money = $money;
        $feeItem->WayId = $this->_id;
        $feeItem->save();
    }

    private $_logs;

    /**
     * 返回运单的操作详情
     */
    public function getLogs() {
        if ($this->_logs == NULL) {
            $this->_logs = Application_Model_WayLog::getByWayId($this->_id);
        }
        return $this->_logs;
    }

    /**
     * 添加运单操作日期
     * @param type $desc 操作说明
     * @param type $isShow 是否在前台显示
     * @param type $operator 操作人
     */
    public function addLog($desc, $isShowFront, $operator) {
        $log = new Application_Model_WayLog();
        $log->DateCreated = date('Y-m-d H:i:s');
        $log->Description = $desc;
        $log->IsShowFront = $isShow;
        $log->Operator = $operator;
        $log->WayId = $this->_id;
        $log->save();
    }

    public function getBillIdDelLog() {
        $logItem = Application_Model_WayLog::getDao()->queryAll(array("wayId" => $this->_id, "and operateType<200 and operateType > " => $this->_interior));
        if ($logItem) {
            foreach ($logItem as $logVal) {
                $logVal->delete();
            }
        }
    }

    private $_weights;

    /**
     * 返回运单的所有重量信息
     * @return type
     */
    public function getWeights() {
        if ($this->_weights == NULL) {
            $this->_weights = Application_Model_WayWeight::getByWayId($this->_id);
        }
        return $this->_weights;
    }

    /**
     * 根据类型获取重量
     * @param type $type
     * @return int
     */
    public function getWeightByType($weightType) {
        $fee = Uuch_Util::first($this->getWeights(), function($item) use($weightType) {
                    return $item->Type == $weightType;
                });
        if ($fee) {
            return $fee->Weight;
        } else {
            switch ($weightType) {
                case Application_Model_WeightType::EstimateVolume:
                    return $this->_volumeWeight;
                case Application_Model_WeightType::ProductWeight:
                    return $this->_productWeight;
                case Application_Model_WeightType::BagWeight:
                    return $this->_bagWeight;
            }
            return 0;
        }
    }

    /**
     * 添加或者修改一个重量信息
     * @param type $type
     * @param type $weight
     */
    public function addWeight($type, $weight) {
        $wayWeight = Application_Model_WayWeight::getWeightByType($this->_id, $type);
        if ($wayWeight) {
            $weightItem = Application_Model_WayWeight::load($wayWeight->id);
        } else {
            $weightItem = new Application_Model_WayWeight();
        }
        $weightItem->Type = $type;
        $weightItem->Weight = $weight;
        $weightItem->WayId = $this->_id;
        $weightItem->save();
        $weights = $this->getWeights();
        $weights[] = $weightItem;
    }

    /**
     * 修改一个重量信息
     * @param type $type
     * @param type $weight
     */
    public function editWeight($type, $weight) {
        $weightItem = Application_Model_WayWeight::getWeightByType($this->_id, $type);
        if ($weightItem == null) {
            $this->addWeight($type, $weight);
            return;
        }
        $weightItem->weight = $weight;
        $weightItem->save();
    }

    /**
     * 运单的最终结算重量
     */
    public function getClosingWeight() {
        $weight = $this->_isVolume && $this->_lastVolumeWeight ? $this->_lastVolumeWeight : $this->_lastWeight;
        return $weight;
    }

    /**
     * 当前重量,如果已经有了结算重量，则显示最终重量，如果没有，就显示预估重量
     */
    public function getCurrentWeight() {
        if ($this->getClosingWeight())
            return $this->getClosingWeight();
        return $this->_isVolume && $this->_volumeWeight ? $this->_volumeWeight : $this->_weight;
    }

    /**
     * 返回运单的所有发货渠道可选项 
     */
    public function getCostOption() {
        return Application_Model_ExpressCost::getByExpressAndCity($this->_shipType, $this->_state, $this->getCurrentWeight());
    }

    /**
     * 获取今日运单详情
     * @param type $state 运单详情
     */
    public static function getcountbill($interior, $problem, $day = null) {
        $where = array();
        $and = '';
        if (!is_null($interior)) {
            $where[" interior = "] = $interior;
            $and = " and ";
        }
        if ($problem != "") {
            $where[$and . " problem = "] = $problem;
            $and = " and ";
            $where[$and . " interior != "] = self::Interior_Cancel;
        } else {
            $where[$and . " ( problem = " . self::Problem_default . " or problem is null or problem = " . self::Problem_Aolve . ") and "] = 1;
            $and = " and ";
        }
        if ($day == 1) {
            $where[$and . " dateCreated > "] = date("Y-m-d");
            $and = " and ";
        }
//        var_dump($where);exit;
        return Application_Model_wayBillItem::getDao()->count($where);
    }

    public static function getBillcount($dateinbegin, $dateinend) {
        $where = "";
        $and = "";
        $where[" status > "] = Application_Model_wayBillItem::STATUS_Processing;
        $and = " and ";
        if ($dateinbegin != "" && $dateinend == "") {
            $where[$and . " dateCreated > "] = $dateinbegin . " 00:00:00";
            $and = " and ";
            $where[$and . " dateCreated < "] = $dateinbegin . " 23:59:59";
            $result = Application_Model_wayBillItem::getDb()->queryAll($where);
            $i = strtotime($dateinbegin);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["zyfk"] = 0;
            $arrre[$i]["zsfk"] = 0;
            $arrre[$i]["zcbj"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["zyfk"] = $arrre[$i]["zyfk"] + $value->shipMoney;
                    $arrre[$i]["zsfk"] = $arrre[$i]["zsfk"] + $value->lastMoney;
                    $arrre[$i]["zcbj"] = $arrre[$i]["zcbj"] + $value->costMoney;
                }
            }
            $where[$and . " agentId = "] = 3;
            $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["hlynum"] = count($hlyresult);
            $arrre[$i]["hlyzyfk"] = 0;
            if ($hlyresult) {
                foreach ($hlyresult as $value) {
                    $arrre[$i]["hlyzyfk"] = $arrre[$i]["hlyzyfk"] + $value->shipMoney;
                }
            }
            $where[$and . " agentId = "] = 2;
            $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["sdnum"] = count($sdresult);
            $arrre[$i]["sdzyfk"] = 0;
            if ($sdresult) {
                foreach ($sdresult as $value) {
                    $arrre[$i]["sdzyfk"] = $arrre[$i]["sdzyfk"] + $value->shipMoney;
                }
            }
        }
        if ($dateinend != "" && $dateinbegin == "") {
            $where[$and . " dateCreated > "] = $dateinend . " 00:00:00";
            $and = " and ";
            $where[$and . " dateCreated < "] = $dateinend . " 23:59:59";
            $result = Application_Model_wayBillItem::getDb()->queryAll($where);
            $i = strtotime($dateinend);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["zyfk"] = 0;
            $arrre[$i]["zsfk"] = 0;
            $arrre[$i]["zcbj"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["zyfk"] = $arrre[$i]["zyfk"] + $value->shipMoney;
                    $arrre[$i]["zsfk"] = $arrre[$i]["zsfk"] + $value->lastMoney;
                    $arrre[$i]["zcbj"] = $arrre[$i]["zcbj"] + $value->costMoney;
                }
            }
            $where[$and . " agentId = "] = 3;
            $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["hlynum"] = count($hlyresult);
            $arrre[$i]["hlyzyfk"] = 0;
            if ($hlyresult) {
                foreach ($hlyresult as $value) {
                    $arrre[$i]["hlyzyfk"] = $arrre[$i]["hlyzyfk"] + $value->shipMoney;
                }
            }
            $where[$and . " agentId = "] = 2;
            $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["sdnum"] = count($sdresult);
            $arrre[$i]["sdzyfk"] = 0;
            if ($sdresult) {
                foreach ($sdresult as $value) {
                    $arrre[$i]["sdzyfk"] = $arrre[$i]["sdzyfk"] + $value->shipMoney;
                }
            }
        }
        if ($dateinend != "" && $dateinbegin != "") {
            $sdate = $dateinbegin <= $dateinend ? $dateinbegin : $dateinend;
            $edate = $dateinbegin >= $dateinend ? $dateinbegin : $dateinend;
            $stime = strtotime($sdate);
            $etime = strtotime($edate);
            for ($i = $stime; $i <= $etime; $i++) {
                $where = "";
                $and = "";
                $where[" status > "] = Application_Model_wayBillItem::STATUS_Processing;
                $and = " and ";
                $where[$and . " dateCreated > "] = date("Y-m-d H:i:s", $i);
                $where[$and . " dateCreated < "] = date("Y-m-d H:i:s", ($i + 86400));
                $result = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$i]["num"] = count($result);
                $arrre[$i]["zyfk"] = 0;
                $arrre[$i]["zsfk"] = 0;
                $arrre[$i]["zcbj"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$i]["zyfk"] = $arrre[$i]["zyfk"] + $value->shipMoney;
                        $arrre[$i]["zsfk"] = $arrre[$i]["zsfk"] + $value->lastMoney;
                        $arrre[$i]["zcbj"] = $arrre[$i]["zcbj"] + $value->costMoney;
                    }
                }
                $where[$and . " agentId = "] = 3;
                $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$i]["hlynum"] = count($hlyresult);
                $arrre[$i]["hlyzyfk"] = 0;
                if ($hlyresult) {
                    foreach ($hlyresult as $value) {
                        $arrre[$i]["hlyzyfk"] = $arrre[$i]["hlyzyfk"] + $value->shipMoney;
                    }
                }
                $where[$and . " agentId = "] = 2;
                $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$i]["sdnum"] = count($sdresult);
                $arrre[$i]["sdzyfk"] = 0;
                if ($sdresult) {
                    foreach ($sdresult as $value) {
                        $arrre[$i]["sdzyfk"] = $arrre[$i]["sdzyfk"] + $value->shipMoney;
                    }
                }
                $i+= 86399;
            }
        }
        if ($dateinend == "" && $dateinbegin == "") {
            $arrre = array();
            $nowYm = date("Y-m");
            $nowd = date("d");
            for ($i = 1; $i <= $nowd; $i++) {
                $where = "";
                $and = "";
                $where[" status > "] = Application_Model_wayBillItem::STATUS_Processing;
                $and = " and ";
                $where[$and . " dateCreated > "] = $nowYm . "-" . $i;
                $where[$and . " dateCreated < "] = $nowYm . "-" . ($i + 1);
                $result = Application_Model_wayBillItem::getDb()->queryAll($where);
                $j = strtotime($nowYm . "-" . $i);
                $arrre[$j]["num"] = count($result);
                $arrre[$j]["zyfk"] = 0;
                $arrre[$j]["zsfk"] = 0;
                $arrre[$j]["zcbj"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$j]["zyfk"] = $arrre[$j]["zyfk"] + $value->shipMoney;
                        $arrre[$j]["zsfk"] = $arrre[$j]["zsfk"] + $value->lastMoney;
                        $arrre[$j]["zcbj"] = $arrre[$j]["zcbj"] + $value->costMoney;
                    }
                }
                $where[$and . " agentId = "] = 3;
                $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$j]["hlynum"] = count($hlyresult);
                $arrre[$j]["hlyzyfk"] = 0;
                if ($hlyresult) {
                    foreach ($hlyresult as $value) {
                        $arrre[$j]["hlyzyfk"] = $arrre[$j]["hlyzyfk"] + $value->shipMoney;
                    }
                }
                $where[$and . " agentId = "] = 2;
                $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$j]["sdnum"] = count($sdresult);
                $arrre[$j]["sdzyfk"] = 0;
                if ($sdresult) {
                    foreach ($sdresult as $value) {
                        $arrre[$j]["sdzyfk"] = $arrre[$j]["sdzyfk"] + $value->shipMoney;
                    }
                }
            }
        }

//        var_dump($arrre);exit;
        return $arrre;
    }

    public static function getBillAll($WayBillSearch, $pagesize, $pageindex) {
        return self::getDao()->queryPage($WayBillSearch->getSearchFileds(), $WayBillSearch->getOrderFileds(), $pagesize, $pageindex);
    }

    public static function getBill_All($where, $pagesize, $pageindex) {
        return self::getDao()->queryPage($where, " dateCreated desc ", $pagesize, $pageindex);
    }

    public static function getFillerAll($WayBillSearch) {
//        var_dump($WayBillSearch->getSearchFileds());
        return self::getDao()->queryAll($WayBillSearch->getSearchFileds(), " datePaid desc ");
    }

    public function getstatustype() {
        if ($this->_status == Application_Model_wayBillItem::STATUS_Complated || $this->_status == Application_Model_wayBillItem::STATUS_Cancel) {
            return false;
        } else {
            return true;
        }
    }

    public function getstatusUnify() {
        if ($this->_interior == self::Interior_AffirmChannel || $this->_interior == self::Interior_OutTransportation || $this->_interior == self::Interior_Overachieve || $this->_interior == self::Interior_Singleno || $this->_interior == self::Interior_Transportation) {
            return true;
        } else {
            return false;
        }
    }

    public function getuser() {
        return new Application_Model_User($this->_userId);
    }

    public function getUserCity() {
        $id = $this->_state;
        return Application_Model_city::load($id);
    }

    public function getagentname() {
        return Application_Model_AgentCompany::load($this->_agentId);
    }

    public function getagentnameByagentId() {
        $agent = Application_Model_WayLog::getByWayIdInteriorType($this->_id, Application_Model_WayLog::Type_BillAffirmAgent);
        if (null != $agent) {
            $name = $agent->DescriptionByAgent->name;
            return $name;
        } else {
            return;
        }
    }

    public static function getInteriorAll() {
        return array(
            Application_Model_wayBillItem::Interior_WaitPay => "待付款"
            , Application_Model_wayBillItem::Interior_Processing => "待受理"
            , Application_Model_wayBillItem::Interior_Confrimed => "待选择渠道"
            , Application_Model_wayBillItem::Interior_Incoice => "待拣货"
            , Application_Model_wayBillItem::Interior_Picking => "待打包"
            , Application_Model_wayBillItem::Interior_Pick => "待确认渠道"
            , Application_Model_wayBillItem::Interior_AffirmChannel => '待交运'
            , Application_Model_wayBillItem::Interior_Outstorage => "已交运"
            , Application_Model_wayBillItem::Interior_System => "已入系统"
            , Application_Model_wayBillItem::Interior_Singleno => "已出转单"
            , Application_Model_wayBillItem::Interior_Transportation => "已上网"
            , Application_Model_wayBillItem::Interior_Achieve => "已经完成"
            , Application_Model_wayBillItem::Interior_PickError => "拣货异常"
            , Application_Model_wayBillItem::Interior_OverSystem => "入系统超期"
            , Application_Model_wayBillItem::Interior_Oversingleno => "转单超期"
            , Application_Model_wayBillItem::Interior_OutTransportation => "上网异常"
            , Application_Model_wayBillItem::Interior_Overachieve => "签收预警"
            , Application_Model_wayBillItem::Interior_Cancel => "已经取消"
            , Application_Model_wayBillItem::Interior_Launch => "未启用"
        );
    }

    public static function getEditInteriorAll() {
        return array(
            Application_Model_wayBillItem::Interior_WaitPay => "待付款"
            , Application_Model_wayBillItem::Interior_Processing => "待受理"
            , Application_Model_wayBillItem::Interior_Confrimed => "待选择渠道"
            , Application_Model_wayBillItem::Interior_Incoice => "待拣货"
            , Application_Model_wayBillItem::Interior_Picking => "待打包"
            , Application_Model_wayBillItem::Interior_Pick => "待确认渠道"
            , Application_Model_wayBillItem::Interior_AffirmChannel => '待交运'
            , Application_Model_wayBillItem::Interior_Outstorage => "已交运"
            , Application_Model_wayBillItem::Interior_System => "已入系统"
            , Application_Model_wayBillItem::Interior_Singleno => "已出转单"
            , Application_Model_wayBillItem::Interior_Transportation => "已上网"
            , Application_Model_wayBillItem::Interior_Achieve => "已经完成"
        );
    }

    public static function getEditStatusAll() {
        return array(
            Application_Model_wayBillItem::STATUS_WaitPay => "待付款"
            , Application_Model_wayBillItem::STATUS_Processing => "等待受理"
            , Application_Model_wayBillItem::STATUS_Confrimed => "已经受理"
            , Application_Model_wayBillItem::STATUS_Sended => "已经发货"
            , Application_Model_wayBillItem::STATUS_Complated => "已经完成"
        );
    }

    public static function getInteriorCorrect() {
        return array(
            Application_Model_wayBillItem::Interior_Confrimed => array("待受理", "已受理")
            , Application_Model_wayBillItem::Interior_Incoice => array("待选择渠道", "已选择渠道")
            , Application_Model_wayBillItem::Interior_Picking => array("待拣货", "已拣货")
            , Application_Model_wayBillItem::Interior_Pick => array("待打包", "已打包")
            , Application_Model_wayBillItem::Interior_AffirmChannel => array("待确认渠道", "已确认渠道")
            , Application_Model_wayBillItem::Interior_Outstorage => array('待交运', "已交运")
            , Application_Model_wayBillItem::Interior_System => array("待入系统", "已入系统")
            , Application_Model_wayBillItem::Interior_Singleno => array("待出转单", "已出转单")
            , Application_Model_wayBillItem::Interior_Transportation => array("待上网", "已上网")
            , Application_Model_wayBillItem::Interior_Achieve => array("待签收", "已签收")
        );
    }

    public function getinteriorname() {
        switch ($this->_interior) {
            case Application_Model_wayBillItem::Interior_WaitPay:
                return "未付款";
                break;
            case Application_Model_wayBillItem::Interior_Processing:
                return "待受理";
                break;
            case Application_Model_wayBillItem::Interior_Confrimed:
                return "待选择渠道";
                break;
            case Application_Model_wayBillItem::Interior_Incoice:
                return "待拣货";
                break;
            case Application_Model_wayBillItem::Interior_Picking:
                return "待打包";
                break;
            case Application_Model_wayBillItem::Interior_Pick:
                return "待确认渠道";
                break;
            case Application_Model_wayBillItem::Interior_AffirmChannel:
                return "待交运";
                break;
            case Application_Model_wayBillItem::Interior_Outstorage:
                return "已交运";
                break;
            case Application_Model_wayBillItem::Interior_PickError:
                return "拣货异常";
                break;
            case Application_Model_wayBillItem::Interior_System:
                return "已入系统";
                break;
            case Application_Model_wayBillItem::Interior_Singleno:
                return "已出转单";
                break;
            case Application_Model_wayBillItem::Interior_Transportation:
                return "已上网";
                break;
            case Application_Model_wayBillItem::Interior_OverSystem:
                return "入系统超期";
                break;
            case Application_Model_wayBillItem::Interior_Oversingleno:
                return "转单超期";
                break;
            case Application_Model_wayBillItem::Interior_OutTransportation:
                return "上网异常";
                break;
            case Application_Model_wayBillItem::Interior_Overachieve:
                return "签收预警";
                break;
            case Application_Model_wayBillItem::Interior_Achieve:
                return "已经完成";
                break;
            case Application_Model_wayBillItem::Interior_Cancel:
                return "已经取消";
                break;
            case Application_Model_wayBillItem::Interior_Launch:
                return "未启用";
                break;
        }
    }

    public function getchannelname() {
        if ($this->_channer) {
            return Application_Model_ExpressChannel::load($this->_channer);
        }
    }

    private $_channelBy;

    /**
     * 返回发货渠道
     */
    public function getChannelBy() {
        if ($this->_channelBy == NULL) {
            $channel = Application_Model_WayLog::getByWayIdInteriorType($this->_id, Application_Model_WayLog::Type_BillAffirmChannel);
            if ($channel) {
                $this->_channelBy = Application_Model_ExpressChannel::load($channel->Description);
            } else {
                $this->_channelBy = Application_Model_ExpressChannel::load($this->_channer);
            }
        }
        return $this->_channelBy;
    }

    /**
     * 获取发货渠道名称
     */
    public function getagentcompname() {
        if ($this->_agentId) {
            return Application_Model_AgentCompany::load((int) $this->_agentId);
        }
    }

    public static function byaddbill($arrre, $idlist) {
        $arrid = explode(",", $idlist);
        $shipFee = 0;
        foreach ($arrid as $key => $value) {
            if ($value != '') {
                $result = Application_Model_StoreItem::load($value);
                $shipFee = $shipFee + $result->cnShipFee;
                if ($result->state == Application_Model_StoreItem::STATUS_Sended) {
                    return 2;
                }
            }
        }

        $billItem = new Application_Model_wayBillItem();
        foreach ($arrre as $key => $value) {
            $billItem->$key = $value;
        }
        $billItem->dateCreated = date("Y-m-d H:i:s");
        $billItem->shipFee = $shipFee;
        $billItem->status = Application_Model_wayBillItem::STATUS_Processing;
        $billItem->shipFeeconfig = 0;
        $billItem->weight = 0;
        $billItem->lastdate = date("Y-m-d H:i:s");
        $billItem->fee = 0;
        $billItem->lwhth = "**";
        $billItem->channer = 0;
        $billItem->reportFee = 0;
        $billItem->interior = Application_Model_wayBillItem::Interior_Processing;
        $billItem->datePaid = date("Y-m-d H:i:s");
//        var_dump($billItem);exit;
        $billItem->save();
        $prices = Application_Model_ExpressPrice::getPricesByCity($billItem->state);
        $SortKey = 0;
        $weight = ($billItem->VolumeWeight > ($billItem->ProductWeight + $billItem->BagWeight)) ? $billItem->VolumeWeight : ($billItem->ProductWeight + $billItem->BagWeight);
        foreach ($prices as $item) {
            if ($item->ExpressId == $billItem->ShipType) {
                $SortKey = $item->getMoneyByweight($weight);
                break;
            }
        }
//        echo $SortKey;exit;
        //选择仓库商品
        foreach ($arrid as $key => $value) {
            if ($value != '') {
                $result = Application_Model_StoreItem::load($value);
                $result->WayId = $billItem->Id;
                $result->State = Application_Model_StoreItem::STATUS_Sended;
                $result->save();
                $billItem->addItem($value);
            }
        }
        //添加费用信息
        $billItem->addFee(Application_Model_FeeType::EstimateShipFee, $SortKey); //预估国际运费
        $billItem->addFee(Application_Model_FeeType::CnShipFee, $shipFee); //国内运费
        $VacuumSeviceFee = 0;
        if ($billItem->IsCompress == 1) {
            $VacuumSeviceFee = 10;
            $billItem->addFee(Application_Model_FeeType::VacuumSeviceFee, 10); //真空费
        }
        $billItem->addFee(Application_Model_FeeType::EstimateSum, ($SortKey + $shipFee + $VacuumSeviceFee)); //预估总费用
        //添加重量信息
        $billItem->addWeight(Application_Model_WeightType::ProductWeight, $billItem->ProductWeight);
        $billItem->addWeight(Application_Model_WeightType::BagWeight, $billItem->BagWeight);
        $billItem->addWeight(Application_Model_WeightType::EstimateWeight, $weight);
        $billItem->addWeight(Application_Model_WeightType::EstimateVolume, $billItem->VolumeWeight);
        Application_Model_Operate::addOperate(0, null, $billItem->billNo, "给会员 " . $billItem->userId . " 手工发起运单（".$billItem->billNo."）", $billItem->userId);
        return 1;
    }

    /**
     * 获取运送方式的信息
     */
    public static function byShipcode($id) {
        return Application_Model_ExpressChannel::load($id);
    }

    /**
     * 快递接口
     * @param type $typeCom 快递类型
     * @param type $typeNu  快递单号
     * @return type
     */
    public static function expressUrl($typeCom, $typeNu) {
        $AppKey = '76f5b960649455ab'; //请将XXXXXX替换成您在http://kuaidi100.com/app/reg.html申请到的KEY
        //优先使用curl模式发送数据
        $url = "http://www.kuaidi100.com/applyurl?key=$AppKey&com=$typeCom&nu=$typeNu";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $get_content = curl_exec($curl);
        curl_close($curl);
        return $get_content;
    }

    /**
     * 发货
     */
    public static function shipments($billid, $uparr, $operate) {

        $result = Application_Model_wayBillItem::load($billid);
        if ($result != '') {
            if ($operate == "single") {
                Application_Model_Operate::addOperate(0, null, $result->billNo, "国际运单已出转单号", $result->userId);
                if ($result->refundMoney == null || $result->refundMoney == "" || $result->refundMoney == 0) {
                    if ($uparr['refundMoney'] != 0) {
                        //修改金额
                        $uwhere[' id = '] = $result->userId;
                        $userdetail = Application_Model_UserAccount::getDao()->queryOne($uwhere);
                        $beforeMoney = $userdetail->money;
                        $userdetail->money = $userdetail->money + $uparr['refundMoney'];
                        $afterMoney = $userdetail->money;
                        $userdetail->save();
                        $history = new Application_Model_UserAccountHistory(); //添加记录
                        $history->type = 1;
                        $history->beforeMoney = $beforeMoney;
                        $history->afterMoney = $afterMoney;
                        $history->comment = '国际运单' . $result->billNo . '退还费';
                        $history->relaseId = $billid;
                        $history->dateCreated = date("Y-m-d H:i:s");
                        $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
                        $history->accountId = $result->userId;
                        $history->save();
                        Application_Model_Operate::addOperate($uparr['refundMoney'], null, $result->billNo, "国际运单已入系统并退款", $result->userId);
                        self::_addFinanceTransaction($userdetail, $beforeMoney, array('order_sn' => $result->billNo, 'money' => $uparr['refundMoney'], 'account_id' => $result->userId));
                    }
                }
            }
            foreach ($uparr as $key => $val) {
                $result->$key = $val;
            }
            $result->stockDate=date('Y-m-d H:i:s');
            $result->save();
            if ($operate == "singment") {
                Application_Model_Operate::addOperate(0, null, $result->billNo, "国际运单发货", $result->userId);
                $storewhere[' wayId'] = $billid;
                $storitemdetail = Application_Model_StoreItem::getDao()->queryAll($storewhere);
                foreach ($storitemdetail as $key => $storeval) {
                    $storeval->state = Application_Model_wayBillItem::STATUS_Sended;
                    $storeval->dateOut = date("Y-m-d H:i:s");
                    $storeval->save();
                }
                $expressItem = Application_Model_ExpressChannel::load($uparr["channer"]);
                if ($expressItem) {
                    if ($expressItem->key) {
                        $logItem = new Application_Model_logisticslogItem();
//                        if ($result->expressId == 7) {
//                            $logItem->opRemark = $expressItem->key . "(悠奇专线)已取件，待出单";
//                        } else {
//                            if ($expressItem->key == "联邦" || $expressItem->key == "DHL" || $expressItem->key == "UPS" || $expressItem->key == "澳大利亚EMS") {
//                                $logItem->opRemark = $expressItem->key . "已取件，待出单";
//                            } else {
//                                $logItem->opRemark = $expressItem->key . "已取件";
//                            }
//                        }
                        $logItem->opRemark = "已交运快递公司";
                        $logItem->opDate = date("Y-m-d H:i:s");
                        $logItem->opUser = 1;
                        $logItem->opState = 0;
                        $logItem->wayId = $billid;
                        $logItem->save();
                    }
                }
            }
            return true;
        } else {
            return false;
        }
    }

    public static function getDelayAll($interior) {
        $where[" interior = "] = $interior;
        $where[" and status = "] = Application_Model_wayBillItem::STATUS_Sended;
        return self::getDao()->queryAll($where);
    }

    public static function bybillNo($billNo) {
        $where[" billNo = "] = $billNo;
        return Application_Model_wayBillItem::getDao()->queryOne($where);
    }

    public function setBillAgent($arrAgent, $description = null) {
        foreach ($arrAgent as $key => $val) {
            $this->$key = $val;
        }
        $this->save();
        $this->addBillLog($arrAgent["interior"]);
        if ($description != null) {
            $this->addBillLog(Application_Model_WayLog::Type_BillVolume, $description);
        }
    }

    public function setWeights($Weight, $type) {
        $this->editWeight($type, $Weight);
    }

    public function inFirstFollow() {
        Application_Model_Operate::addOperate(0, null, $this->_billNo, "国际运单发货", $this->_userId);
        $storewhere[' wayId'] = $this->_id;
        $storitemdetail = Application_Model_StoreItem::getDao()->queryAll($storewhere);
        foreach ($storitemdetail as $storeval) {
            $storeval->state = Application_Model_wayBillItem::STATUS_Sended;
            $storeval->dateOut = date("Y-m-d H:i:s");
            $storeval->save();
        }
//        $logItem = Application_Model_logisticslogItem::getByWayId($this->_id);
//        if (!$logItem) {
//            $wayLogItem = Application_Model_WayLog::getByWayIdInteriorType($this->_id, Application_Model_WayLog::Type_BillAffirmChannel); 
//            $channerNo = $wayLogItem?$wayLogItem->Description:$this->_channer;
//            $expressItem = Application_Model_ExpressChannel::load($channerNo);
//            $ReceptionExpressItem = Application_Model_Express::load($expressItem->expressId);
//            $logItem = new Application_Model_logisticslogItem();
//            $logItem->opRemark = $ReceptionExpressItem->Name . "已取件，待出单";
//            $logItem->opDate = date("Y-m-d H:i:s");
//            $logItem->opUser = 1;
//            $logItem->opState = 0;
//            $logItem->wayId = $this->_id;
//            $logItem->save();
//        }
    }

    /*
     * 受理
     */

    public static function getUpstatus($id, $payWeight) {
        $result = Application_Model_wayBillItem::load($id);
        if ($result != '') {
            if ($result->status == Application_Model_wayBillItem::Interior_Processing) {
                $result->status = Application_Model_wayBillItem::STATUS_Confrimed;
                $result->interior = Application_Model_wayBillItem::Interior_Confrimed;
                $result->paymentWeight = $payWeight * 1000;
                $result->logistics = "";
                if ($result->ExpressBy->isInvoice == 0) {
                    $result->isInvoice = 1;
                }
                $result->save();
                $result->addBillLog(Application_Model_wayBillItem::Interior_Confrimed);
                Application_Model_Operate::addOperate(0, null, $result->billNo, "受理国际运单", $result->userId);
            //返利
            $recommendItem = Application_Model_Recommend::ByUserIdReUserId($result->UserId, null);
            if($recommendItem){ 
                   $rewardItem1=Application_Model_Reward::bybillNo($result->BillNo);          
                   if($rewardItem1) continue;  
                    $rewardItem = new Application_Model_Reward();
                    $rewardItem->UserId = $result->UserId;
                    $rewardItem->BillNo = $result->BillNo;
                    $rewardItem->Money = "0.00";
                    $rewardItem->Rebate = "0.00";
                    $rewardItem->ReUserId = $recommendItem->ReUserId;
                    $rewardItem->IsAbled = Application_Model_Reward::IsAbled_Unfinished;
                    $rewardItem->CreateTime = date("Y-m-d H:i:s");
                    $rewardItem->save();                    
                }
            } else {
                return 0;
            }
        }
        return 1;
    }

    public function addBillLog($interior, $description = null, $type = null) {

        $billLogItem = Application_Model_WayLog::getByWayIdInteriorType($this->_id, $interior);
        if (!$billLogItem) {
            $billLogItem = new Application_Model_WayLog();
            $billLogItem->wayId = $this->_id;
            $billLogItem->operateType = $interior;
        }
        $billLogItem->dateCreated = date("Y-m-d H:i:s");
        if ($type == "system") {
            $billLogItem->operator = "admin";
        } else {
            $billLogItem->operator = Uuch_Util::getUserNikeName();
        }
        if ($description != null) {
            $billLogItem->description = $description;
        } else {
            $billLogItem->description = "运单状态更改为：" . $this->getinteriorname();
        }
        $billLogItem->type = Application_Model_WayLog::Type_Bill;
        $billLogItem->save();
    }

    /**
     * 取消运单
     */
    public static function getcancel($id) {
        $result = Application_Model_wayBillItem::load($id);
        if ($result != '') {
            if ($result->status == Application_Model_wayBillItem::STATUS_Processing || $result->status == Application_Model_wayBillItem::STATUS_ExpressBack) {
                $result->status = Application_Model_wayBillItem::STATUS_Cancel;
                if ($result->discountFee > 0) {
                    $couponItem = Application_Model_Coupon::byrelevance($result->id);
                    if ($couponItem) {
                        $couponItem->status = 1;
                        $couponItem->useTime = "";
                        $couponItem->relevance = "";
                        $couponItem->save();
                    }
                }
                if ($result->problem == self::Problem_Appear) {
                    $result->problem = self::Problem_Cancel;
                }
                $result->addProblemWay(Application_Model_ProblemWay::Problem_Cancel, null);
                $result->save();
                Application_Model_Operate::addOperate(0, null, $result->billNo, "取消国际运单", $result->userId);
                foreach ($result->getStoreItems() as $storeVal) {
                    $storeVal->wayId = 0;
                    $storeVal->state = Application_Model_StoreItem::STATUS_InStored;
                    $storeVal->interior = Application_Model_StoreItem::Interior_InStored;
                    $storeVal->save();
                }

                if ($result->interior > self::Interior_WaitPay) {
                    $userdetail = Application_Model_UserAccount::load($result->userId);
                    $beforeMoney = $userdetail->money;
                    $refundSum = $result->getFeeByType(Application_Model_FeeType::EstimateSum);
                    $userdetail->money = $userdetail->money + $refundSum;
                    $afterMoney = $userdetail->money;
                    $userdetail->save();
                    $history = new Application_Model_UserAccountHistory();
                    $history->type = 1;
                    $history->beforeMoney = $beforeMoney;
                    $history->afterMoney = $afterMoney;
                    $history->comment = '运单：' . $result->billNo . '退单费';
                    $history->dateCreated = date("Y-m-d H:i:s");
                    $history->relaseId = $id;
                    $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
                    $history->accountId = $result->userId;
                    $history->save();
                    $user = Application_Model_User::load($result->userId);
                    $financeData = array(
                        'transaction_number' => '',
                        'trader' => 'account-number-dr',
                        'customer_id' => $result->userId,
                        'member' => 'admin',
                        'amount' => $refundSum,
                        'currency' => 'CNY',
                        'customer_name' => $user->nikename,
                        'rate' => '1',
                        'rate_amount' => '0',
                        'period_start' => $beforeMoney,
                        'period_end' => $afterMoney,
                        'business_type' => 'gjydqxtk',
                        'order_sn' => $result->billNo,
                        'attribute' => json_encode(array(
                            'waybill_status' => '运单取消',

                        )),
                        'remark' => $result->interiorRemark ? $result->interiorRemark : '',
                        'created_at' => date('Y-m-d H:i:s')
                    );

                    self::_addFinance($userdetail, $financeData);
                    $financeData['trader'] = 'backend-account-cr';
                    self::_addFinance($userdetail, $financeData);
                    Application_Model_Operate::addOperate($refundSum, null, $result->billNo, "取消国际运单退款", $result->userId);
                }
                return 2;
            }
            return 22;
        } else {
            return 6;
        }
    }

    public static function getDelaySystemAll() {
        $where[" interior = "] = Application_Model_wayBillItem::Interior_Outstorage;
        return self::getDao()->queryAll($where);
    }

    public function getlocationName() {
        $result = Application_Model_StoreLocation::getDao()->queryAll(array("userId" => $this->_userId));
        if ($result) {
            $locationName = "";
            foreach ($result as $value) {
                $locationName.= $value->locationNo . ",";
            }
            return $locationName;
        } else {
            return "还没有绑定仓库位，请耐心寻找。";
        }
    }

    public function getstorecount() {
        $where[" userid = "] = $this->_userId;
        $where[" and state in "] = "(" . Application_Model_StoreItem::STATUS_InStored . "," . Application_Model_StoreItem::STATUS_CheckIn . "," . Application_Model_StoreItem::STATUS_Picking . ")";
        $where[" and (isdelete = 0 or isdelete is null) and "] = 1;
        $countStore = Application_Model_StoreItem::getDao()->count($where);
        if ($countStore == 0) {
            Application_Model_StoreLocation::byUseridRemoveLocation($this->_userId);
        }
    }

    /**
     * 返回此运单各个代理公司的报价
     */
    public function getExpressReportCost() {
        $weight = $this->getLastEnterWeight();
        $ids = Uuch_Util::select($this->getExpressBy()->getRelationChannel(), function($item) {
                    return $item->Id;
                });
        return Application_Model_ExpressCost::getCostByChannelCityWeight($ids, $this->_state, $weight);
    }

    /**
     * 返回最后输入的重量,一般是最后的重量信息才是最准的
     */
    public function getLastEnterWeight() {
        return 1000;
    }

    public static function getChannelIdWeightByExpress($expressId, $weight, $city) {
        $channelItem = Application_Model_Expressbychannel::getExpressIdByChannel($expressId);
        $channelId = "(";
        foreach ($channelItem as $value) {
            $channelId.= $value->expressChannelId . ",";
        }
        $channelId.= "0)";
        $where[" channelId in "] = $channelId;
        $where[" and cityId = "] = $city;
        $where[" and weight = "] = (int) ($weight / 1000) + 1;

        return Application_Model_ExpressCost::getDao()->queryAll($where, " price asc");
    }

    public function AddSingle() {
        $where[" outstoreno = "] = $this->_agentNo;
        $singItem = Application_Model_Single::getDao()->queryOne($where);
        if (!$singItem) {
            $singItem = new Application_Model_Single();
        }
        $singItem->outstoreno = $this->_agentNo;
        $singItem->agentid = $this->_agentId;
        if ($this->_logistics) {
            $singItem->ischange = 1;
        }
        $singItem->save();
        return true;
    }

    public function getbillurl() {
        if ($this->_interior == Application_Model_wayBillItem::Interior_Launch) {
            $visitingItem = Application_Model_VisitingServer::ByWayId($this->_id);
            return "/admini/visiting/vsdetail/id/" . $visitingItem->Id;
        } else {
            return "/admini/managewaybill/billaccep/id/" . $this->_id;
        }
    }

    public function getBillNoInvoice() {
        return Application_Model_invoice::bybillNo($this->_billNo);
    }

    public static function getBillIdAffirm($idlist) {
        $arrid = explode(",", $idlist);
        for ($i = 0; $i < count($arrid); $i++) {
            $result = Application_Model_wayBillItem::load($arrid[$i]);
            if ($result != '') {
                if ($result->interior == Application_Model_wayBillItem::Interior_AffirmChannel || $result->status == Application_Model_wayBillItem::STATUS_Confrimed) {
                    $result->status = Application_Model_wayBillItem::STATUS_Sended;
                    $result->interior = Application_Model_wayBillItem::Interior_Outstorage;
                    $result->dateSend = date("Y-m-d H:i:s");
                    $result->logistics = "";
                    $result->save();
                    $comment = "国际运单交运";
                    $result->waybillExchangeScore($comment);
                    $result->AnalysisRecommend($result->UserId);
                    $result->addBillLog(Application_Model_wayBillItem::Interior_Outstorage);
                    Application_Model_Operate::addOperate(0, null, $result->billNo, "国际运单交运", $result->userId);
                    foreach ($result->getStoreItems() as $storeVal) {
                        if ($storeVal->interior == Application_Model_StoreItem::Interior_Pack) {
                            $storeVal->state = Application_Model_StoreItem::STATUS_Sended;
                            $storeVal->interior = Application_Model_StoreItem::Interior_OutStore;
                            $storeVal->dateOut = date("Y-m-d H:i:s");
                            $storeVal->save();
                        }
                    }
                    $result->inFirstFollow();
                } else {
                    return 0;
                }
            }
            $visitingItem = Application_Model_VisitingServer::getByWayId($arrid[$i]);
            if ($visitingItem != null)
                $visitingItem->SendTo();
        }
        return 1;
    }

    public function editBillInterior($interior) {
        if ($interior == self::Interior_Achieve || $interior == self::Interior_Cancel || $interior == self::Interior_Processing) {
            $this->_status = $interior;
        } else if ($interior < self::Interior_Outstorage) {
            $this->_status = self::STATUS_Confrimed;
        } else {
            $this->_status = self::STATUS_Sended;
        }
        $this->_interior = $interior;
        $this->save();
        $this->getBillIdDelLog();
        Application_Model_Operate::addOperate(0, null, $this->_billNo, "修改国际运单的后台状态为：".$this->getinteriorname(), $this->_userId);
        return 2;
    }

    public function editBillStatus($status) {
        $this->_status = $status;
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_billNo, "修改国际运单的前台状态为：".$this->getStatusName(), $this->_userId);
        return 2;
    }

    public static function affirmfind($billid, $storeid) {
        $billItem = self::load($billid);
        if ($billItem->interior == Application_Model_wayBillItem::Interior_PickError) {
            $billstoreItem = Application_Model_WayItem::getWayIdStoreIdByStatus($billid, $storeid);
            if ($billstoreItem->status == Application_Model_WayItem::Status_Lose) {
                $billstoreItem->status = Application_Model_WayItem::Status_Picking;
                $billstoreItem->save();
                foreach ($billItem->getItems() as $itemVal) {
                    if ($itemVal->status == Application_Model_WayItem::Status_Initial || $itemVal->status == Application_Model_WayItem::Status_Lose) {
                        return 1;
                    }
                }
                $billItem->interior = self::Interior_Picking;
                $billItem->save();
                $billItem->addBillLog(self::Interior_Picking);
                return 1;
            } else {
                return 3;
            }
        } else {
            return 2;
        }
    }

    public function addProblem($content) {
        Application_Model_Operate::addOperate(0, null, $this->_billNo, "标记问题运单并发送站内信和邮件通知用户", $this->_userId);
        $title = "尊敬的客户，您好！您的运单($this->_billNo)出现问题。";
        $type = Application_Model_problem::TYPE_BILL;
        $issuetype = Application_Model_problem::SUE_YOUQI;
        Application_Model_problem::addProblem($this->_userId, $this->_id, $type, $issuetype, $title, $content);
        $this->addProblemWay(Application_Model_ProblemWay::Problem_StayUser, null);
        $this->addProblemSchedule("运单出现问题", null);
        $messageItem = new Application_Model_Mail();
        $messageItem->title = $title;
        $messageItem->userId = $this->_userId;
        $messageItem->type = 2;
        $messageItem->status = 0;
        $messageItem->message = $content;
        $messageItem->dateCreated = date("Y-m-d H:i:s");
        $messageItem->save();
        $userItem = Application_Model_User::load($this->_userId);
        Application_Model_Email::sendMail($this->_userId, $userItem->email, $title, $content);
        return true;
    }

    public function addMessage($content) {
        $title = "尊敬的客户，您好！您的运单($this->_billNo)出现新的留言。";
        $type = Application_Model_problem::TYPE_BILL;
        $issuetype = Application_Model_problem::SUE_YOUQI;
        Application_Model_problem::addProblem($this->_userId, $this->_id, $type, $issuetype, $title, $content);
        if ($this->_problem == self::Problem_Aolve) {
            $this->addIsMessage(Application_Model_ProblemWay::IsMessage_User);
        } else {
            $this->addIsMessage(Application_Model_ProblemWay::Problem_StayUser);
        }
        return true;
    }

    public function addProblemUser($content) {
        $type = Application_Model_problem::TYPE_BILL;
        $issuetype = Application_Model_problem::SUE_USER;
        Application_Model_problem::addProblem($this->_userId, $this->_id, $type, $issuetype, null, $content);
        if ($this->_status == Application_Model_wayBillItem::STATUS_ExpressBack) {
            $problemItem = Application_Model_ProblemWay::getByTypeWayId($this->_id);
            if ($problemItem->status == Application_Model_ProblemWay::Problem_StayUser || $problemItem->status == Application_Model_ProblemWay::Problem_StayUuch) {
                $this->addProblemWay(Application_Model_ProblemWay::Problem_StayUuch, null);
                $this->addProblemSchedule("问题协商中", null);
            }
        } else {
            $this->addIsMessage(Application_Model_ProblemWay::IsMessage_Uuch);
        }
        return true;
    }

    public function addIsMessage($IsMessage) {
        $problemItem = Application_Model_ProblemWay::getByTypeWayId($this->_id);
        if (!$problemItem) {
            $problemItem = new Application_Model_ProblemWay();
        }
        $problemItem->wayId = $this->_id;
        if ($this->_problem == self::Problem_Aolve) {
            $problemItem->IsMessage = $IsMessage;
        } else {
            $problemItem->Status = $IsMessage;
        }
        $problemItem->DateMessage = date("Y-m-d H:i:s");
        $problemItem->type = Application_Model_ProblemWay::Type_Bill;
        $problemItem->save();
    }

    public function addProblemWay($status, $schedule) {
        $problemItem = Application_Model_ProblemWay::getByTypeWayId($this->_id);
        if (!$problemItem) {
            $problemItem = new Application_Model_ProblemWay();
        }
        $problemItem->wayId = $this->_id;
        $problemItem->status = $status;
        $problemItem->schedule = $schedule;
        $problemItem->type = Application_Model_ProblemWay::Type_Bill;
        $problemItem->save();
    }

    public function addProblemSchedule($content, $schedule, $crdate = null) {
        $problemScheduleItem = new Application_Model_ProblemSchedule();
        $problemScheduleItem->wayId = $this->_id;
        $problemScheduleItem->content = $content;
        $problemScheduleItem->operateName = Uuch_Util::getUserNikeName();
        $problemScheduleItem->schedule = $schedule;
        $problemScheduleItem->dateCreated = ($crdate == null ? date("Y-m-d H:i:s") : $crdate);
        $problemScheduleItem->type = Application_Model_ProblemSchedule::Type_Bill;
        $problemScheduleItem->save();
    }

    public static function getDateByWayBill($stime, $etime) {
        if ($stime != null) {
            $where[' dateSend >='] = $stime;
        } else {
            $where[' dateSend >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateSend <='] = $etime . " 23:59:59";
        }
        $where[" and status in "] = "(" . Application_Model_wayBillItem::STATUS_Sended . "," . Application_Model_wayBillItem::STATUS_Complated . ")";
        $billItem = Application_Model_wayBillItem::getDao()->queryAll($where);
        $money = 0;
        if ($billItem) {
            foreach ($billItem as $billVal) {
                $money += $billVal->getFeeByType(Application_Model_FeeType::EstimateSum);
            }
        }
        return $money;
    }

    public static function getDateByBill($stime, $etime) {
        if ($stime != null) {
            $where[' dateSend >='] = $stime;
        } else {
            $where[' dateSend >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateSend <='] = $etime . " 23:59:59";
        }
        $where[" and status in "] = "(" . Application_Model_wayBillItem::STATUS_Sended . "," . Application_Model_wayBillItem::STATUS_Complated . ")";
        $where[" and (problem = " . self::Problem_default . " or problem = " . self::Problem_Aolve . " or problem is null ) and "] = 1;
        return Application_Model_wayBillItem::getDao()->count($where);
    }

    public static function getProblemCount($stime, $etime) {
        if ($stime != null) {
            $where[' dateCreated >='] = $stime;
        } else {
            $where[' dateCreated >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateCreated <='] = $etime . " 23:59:59";
        }
        $where[" and (problem = " . self::Problem_default . " or problem = " . self::Problem_Aolve . " or problem is null ) and "] = 1;
//        var_dump($where);exit;
        return Application_Model_wayBillItem::getDao()->count($where);
    }

    /**
     * 拣货功能点
     * @param type $barcode  拣货的商品的仓库编号
     * @return int 100 全部拣玩 1 商品正确 2 商品错误
     */
    public function packstore($barcode) {
        $ckpicking = false;
        $ckpick = 0;
        $storedetail = $this->getItems();
        if ($storedetail) {
            foreach ($storedetail as $storeval) {
                $storeItem = $storeval->StoreItem;
                if ($storeItem->barcode == $barcode) {
                    $storeval->status = Application_Model_WayItem::Status_Picking;
                    $storeval->save();
                    $storeItem->interior = Application_Model_StoreItem::Interior_PickIng;
                    $storeItem->save();
                    Application_Model_Operate::addOperate(0, null, $barcode, "运单捡货", $this->_userId);
                    $ckpicking = true;
                }
                if ($storeval->status == Application_Model_WayItem::Status_Picking) {
                    $ckpick++;
                }
            }
            if ($ckpicking) {
                if ($ckpick == count($storedetail)) {
                    return 100;            //全部捡完
                } else {
                    return 1;             //包裹对应
                }
            } else {
                return 2;                 //包裹不对应
            }
        } else {
            return 0;                     //该运单没有货物
        }
    }

    /**
     * 设置该运单拣货异常
     * @return int 2 设置成功 1 设置失败
     */
    public function affirmPickError() {
        if ($this->_status == self::STATUS_Confrimed && ($this->_interior == self::Interior_Incoice || $this->_interior == self::Interior_PickError)) {
            $this->_interior = self::Interior_PickError;
            $this->save();
            foreach ($this->getItems() as $itemVal) {
                if ($itemVal->status == Application_Model_WayItem::Status_Initial || $itemVal->status == Application_Model_WayItem::Status_Lose) {
                    $itemVal->status = Application_Model_WayItem::Status_Lose;
                    $itemVal->save();
                    $itemVal->StoreItem->interior = Application_Model_StoreItem::Interior_LoseStore;
                    $itemVal->StoreItem->save();
                }
            }
            Application_Model_Operate::addOperate(0, null, $this->_billNo, "国际运单捡货异常", $this->_userId);
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * 拣货完成 
     * @return int
     */
    public function affirmPick() {
        if ($this->_status == self::STATUS_Confrimed && ($this->_interior == self::Interior_Incoice || $this->_interior == self::Interior_PickError)) {
            $this->_interior = self::Interior_Picking;
            $this->save();
            foreach ($this->getItems() as $itemVal) {
                if ($itemVal->status != Application_Model_WayItem::Status_Lose) {
                    $itemVal->status = Application_Model_WayItem::Status_Picking;
                    $itemVal->save();
                    $itemVal->StoreItem->interior = Application_Model_StoreItem::Interior_PickIng;
                } else {
                    $itemVal->StoreItem->interior = Application_Model_StoreItem::Interior_LoseStore;
                }
                $itemVal->StoreItem->save();
            }
            $this->addBillLog(Application_Model_wayBillItem::Interior_Picking);
            Application_Model_Operate::addOperate(0, null, $this->_billNo, "国际运单捡货完成", $this->_userId);
            return 1;
        } else {
            return 0;
        }
    }

    /*
     * 已打包待确认渠道
     */

    public function affirmPickIng($agentNo, $logistics, $totalWeight, $totalVolume, $splitArr) {
        if ($this->_status == Application_Model_wayBillItem::STATUS_Confrimed && $this->_interior == Application_Model_wayBillItem::Interior_Picking) {
            $this->_agentNo = $agentNo;
            $this->_logistics = $logistics;
            $this->_interior = Application_Model_wayBillItem::Interior_Pick;
            $this->save();
            Application_Model_Operate::addOperate(0, null, $this->_billNo, "国际运单打包完成", $this->_userId);
            $this->addBillLog(Application_Model_wayBillItem::Interior_Pick);

            $this->AddSingle();
            $this->editWeight(Application_Model_WeightType::FirstWeight, $totalWeight * 1000);
            $this->editWeight(Application_Model_WeightType::FirstVolume, $totalVolume * 1000);
            foreach ($this->getStoreItems() as $itemVal) {
                $itemVal->interior = Application_Model_StoreItem::Interior_Pack;
                $itemVal->save();
            }
            Application_Model_WaySplit::addSplit($this->_id, $splitArr);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 已确认渠道待交运
     * @return int
     */
    public function affirmChannel() {
        if ($this->_status == Application_Model_wayBillItem::STATUS_Confrimed && $this->_interior == Application_Model_wayBillItem::Interior_Pick) {
            $this->_interior = Application_Model_wayBillItem::Interior_AffirmChannel;
            $this->save();
            Application_Model_Operate::addOperate(0, null, $this->_billNo, "国际运单再次确认渠道完成", $this->_userId);
            $this->addBillLog(Application_Model_wayBillItem::Interior_AffirmChannel);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 再次确认渠道修改了渠道
     */
    public function affirmEditChannel($agentid, $channer) {
        if ($this->_status == Application_Model_wayBillItem::STATUS_Confrimed && $this->_interior == Application_Model_wayBillItem::Interior_Pick) {
            $this->_interior = Application_Model_wayBillItem::Interior_AffirmChannel;
            $this->save();
            Application_Model_Operate::addOperate(0, null, $this->_billNo, "国际运单再次确认渠道时修改了渠道", $this->_userId);
            $this->addBillLog(Application_Model_wayBillItem::Interior_AffirmChannel);
            $this->addBillLog(Application_Model_WayLog::Type_BillAffirmAgent, $agentid);
            $this->addBillLog(Application_Model_WayLog::Type_BillAffirmChannel, $channer);
            return 1;
        } else {
            return 0;
        }
    }

    public function affirmOut() {
        if ($this->_status == Application_Model_wayBillItem::STATUS_Confrimed && $this->_interior == Application_Model_wayBillItem::Interior_AffirmChannel) {
            $this->_status = Application_Model_wayBillItem::STATUS_Sended;
            $this->_interior = Application_Model_wayBillItem::Interior_Outstorage;
            $this->_dateSend = date("Y-m-d H:i:s");
            $this->save();
            $comment = "国际运单交运";
            $this->waybillExchangeScore($comment);
            $this->AnalysisRecommend($this->_userId);
            Application_Model_Operate::addOperate(0, null, $this->_billNo, "国际运单交运完成", $this->_userId);
            foreach ($this->getStoreItems() as $storeVal) {
                if ($storeVal->interior == Application_Model_StoreItem::Interior_Pack) {
                    $storeVal->interior = Application_Model_StoreItem::Interior_OutStore;
                    $storeVal->state = Application_Model_StoreItem::STATUS_Sended;
                    $storeVal->dateOut = date("Y-m-d H:i:s");
                    $storeVal->save();
                }
            }
            $this->inFirstFollow();
            $visitingItem = Application_Model_VisitingServer::getByWayId($this->_id);
            if ($visitingItem != null)
                $visitingItem->SendTo();
            $this->addBillLog(Application_Model_wayBillItem::Interior_Outstorage);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 国际运单消费得积分
     */
    public function waybillExchangeScore($comment) {
        $userItem = Application_Model_UserAccount::addAccount($this->_userId);
        $userItem->MoneyExchangeScore(Application_Model_UserAccount::ExchangeScore_Waybill, $this->getFeeByType(Application_Model_FeeType::EstimateSum), $comment);
    }

    /**
     * 是否是被推荐用户
     */
    private function AnalysisRecommend($userId) {
        $recommendItem = Application_Model_Recommend::ByUserIdReUserId($userId, null);
        if ($recommendItem) {
            $accountItem = Application_Model_UserAccount::addAccount($recommendItem->ReUserId);
            $accountItem->TaskExchangeScore("reWay");
            $recommendItem->IsAbled = Application_Model_Recommend::IsAbled_Complete;
            $recommendItem->save();
        }
    }

    /**
     * 活动后国际运单完成后在给一次成长值，代购页面一样
     */
    public function ActivityConsumeExchangeScore() {
        $rechargeItem = Application_Model_RechargeBill::getByUserId($this->_userId, Application_Model_PayBill::PAY_STATUS_SUCCESS, Application_Model_RechargeBill::RechargeActivityStart, Application_Model_RechargeBill::RechargeActivityEnd);
        if (!$rechargeItem) {
            return;
        }
        $sumMoney = 0;
        foreach ($rechargeItem as $rechargeVal) {
            if ($rechargeVal->Money >= 1000) {
                $sumMoney += $rechargeVal->Money;
            }
        }

        $wayMoney = $this->getWayMoney($this->_userId);
        $orderMoney = $this->getOrderMoney($this->_userId);
        if ($sumMoney > ($wayMoney + $orderMoney)) {
            $comment = "国际运单签收，情人节充值活动二次赠送成长值";
            $this->waybillExchangeScore($comment);
        }
    }

    /**
     * 获取活动开始后国际运单消费多少金额
     * @param type $userId 用户Id
     * @return type 运单消费总金额
     */
    private function getWayMoney($userId) {
        $WayBillSearch = new Application_Model_Filter_WayBillSearch();
        $WayBillSearch->userid = $userId;
        $WayBillSearch->status = Application_Model_wayBillItem::STATUS_Complated;
        $WayBillSearch->starttime = Application_Model_RechargeBill::RechargeActivityStart;
        $wayItem = Application_Model_wayBillItem::getDao()->queryAll($WayBillSearch->getSearchFileds());
        $wayMoney = 0;
        foreach ($wayItem as $wayVal) {
            $wayMoney += $wayVal->lastMoney;
        }
        return $wayMoney;
    }

    /**
     * 获取活动开始后代购消费多少金额
     * @param type $userId 用户Id
     * @return type 代购消费总金额
     */
    private function getOrderMoney($userId) {
        $orderSearch = new Application_Model_Filter_OrderSearch();
        $orderSearch->userid = $userId;
        $orderSearch->status = Application_Model_Order::STATUS_INSTORE;
        $orderSearch->starttime = Application_Model_RechargeBill::RechargeActivityStart;
        $orderItem = Application_Model_Order::getDao()->queryAll($orderSearch->getSearchFileds());
        $orderMoney = 0;
        foreach ($orderItem as $orderVal) {
            $orderMoney += $orderVal->Sum;
        }
        return $orderMoney;
    }

    public function affirmProblemReturnCancel() {
        if ($this->_status != Application_Model_wayBillItem::STATUS_Complated && $this->_status != Application_Model_wayBillItem::Interior_Cancel) {
            if ($this->_interior >= Application_Model_wayBillItem::Interior_Outstorage && $this->_interior != Application_Model_wayBillItem::Interior_PickError) {
                $this->addProblemWay(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_Default);
                $this->addProblemSchedule("问题运单申请整个退件", Application_Model_ProblemWay::Schedule_Default);
                Application_Model_Operate::addOperate(0, null, $this->_billNo, "问题运单申请整个退件", $this->_userId);
            } else {
                $this->addProblemWay(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_InUuch);
                $this->addProblemSchedule("问题运单整个退件，已在悠奇仓库，等待入库", Application_Model_ProblemWay::Schedule_InUuch);
                Application_Model_Operate::addOperate(0, null, $this->_billNo, "问题运单整个退件，已在悠奇仓库，等待入库", $this->_userId);
                foreach ($this->getStoreItems() as $itemVal) {
                    $itemVal->interior = Application_Model_StoreItem::Interior_ReturnIng;
                    $itemVal->save();
                }
            }
            return 1;
        } else {
            return 0;
        }
    }

    public function affirmProblemPartReturn() {
        if ($this->_status != Application_Model_wayBillItem::STATUS_Complated && $this->_status != Application_Model_wayBillItem::Interior_Cancel) {
            if ($this->_interior == self::Interior_Achieve || $this->_interior == self::Interior_Cancel || $this->_interior == self::Interior_Processing) {
                $this->_status = $this->_interior;
            } else if ($this->_interior < self::Interior_Outstorage) {
                $this->_status = self::STATUS_Confrimed;
            } else {
                $this->_status = self::STATUS_Sended;
            }
            $this->_problem = self::Problem_Aolve;
            $this->save();
            if ($this->_interior >= Application_Model_wayBillItem::Interior_Outstorage && $this->_interior != Application_Model_wayBillItem::Interior_PickError) {
                $this->addProblemWay(Application_Model_ProblemWay::Problem_PartReturn, Application_Model_ProblemWay::Schedule_Default);
                $this->addProblemSchedule("问题运单申请部分不符合规范的物品退回", Application_Model_ProblemWay::Schedule_Default);
                Application_Model_Operate::addOperate(0, null, $this->_billNo, "问题运单申请部分不符合规范的物品退回", $this->_userId);
            } else {
                $this->addProblemWay(Application_Model_ProblemWay::Problem_PartReturn, Application_Model_ProblemWay::Schedule_InUuch);
                $this->addProblemSchedule("问题运单部分不符合规范的物品退回，已在悠奇仓库，等待入库", Application_Model_ProblemWay::Schedule_InUuch);
                Application_Model_Operate::addOperate(0, null, $this->_billNo, "问题运单部分不符合规范的物品退回，已在悠奇仓库，等待入库", $this->_userId);
            }
            return 1;
        } else {
            return 0;
        }
    }

    public function ScheduleDefault($ScheduleType) {
        if ($this->_status != Application_Model_wayBillItem::STATUS_Complated && $this->_status != Application_Model_wayBillItem::Interior_Cancel) {
            foreach ($this->getStoreItems() as $itemVal) {
                if ($itemVal->interior == Application_Model_StoreItem::Interior_OutStore) {
                    $itemVal->interior = Application_Model_StoreItem::Interior_Withhold;
                    $itemVal->save();
                }
            }
            if ($ScheduleType != "渠道商退包") {
                $this->addProblemWay(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_ApplyFor);
                $this->addProblemSchedule("问题运单已申请整个退件", Application_Model_ProblemWay::Schedule_ApplyFor);
            } else {
                $this->addProblemWay(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_InChannel);
                $this->addProblemSchedule("问题运单已申请整个退件", Application_Model_ProblemWay::Schedule_InChannel);
            }
            $this->addProblemSchedule($ScheduleType, Application_Model_ProblemWay::Schedule_Reason);
            return 1;
        } else {
            return 0;
        }
    }

    public function delProblemSchedule() {
        $scheduleItem = Application_Model_ProblemSchedule::getByWayId($this->_id);
        if ($scheduleItem) {
            foreach ($scheduleItem as $scheduleVal) {
                $scheduleVal->delete();
            }
            return 1;
        } else {
            return 0;
        }
    }

    public function applyForRefund() {
        $problemWayItem = Application_Model_ProblemWay::getByTypeWayId($this->_id);
        if ($problemWayItem) {
            $problemWayItem->isReturnMoney = 1;
            $problemWayItem->save();
            $this->addProblemSchedule("该问题运单用户已申请提前退款", null);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 退件运单商品入库并退款
     */
    public function ScheduleInUuch() {
        if ($this->_status != Application_Model_wayBillItem::STATUS_Complated && $this->_status != Application_Model_wayBillItem::Interior_Cancel) {
            $this->_status = Application_Model_wayBillItem::STATUS_Cancel;
            $this->_problem = self::Problem_Cancel;
            $this->save();
            foreach ($this->getStoreItems() as $itemVal) {
                $itemVal->interior = Application_Model_StoreItem::Interior_ReturnStore;
                $itemVal->save();
            }
            if ($this->_discountFee > 0) {
                $couponItem = Application_Model_Coupon::byrelevance($this->_id);
                if ($couponItem) {
                    $couponItem->status = 1;
                    $couponItem->useTime = "";
                    $couponItem->relevance = "";
                    $couponItem->save();
                }
            }
            $uwhere[' id = '] = $this->_userId;
            $userdetail = Application_Model_UserAccount::getDao()->queryOne($uwhere);
            $beforeMoney = $userdetail->money;
            if ($this->_interior > self::Interior_Outstorage && $this->_interior != self::Interior_PickError) {
                $userdetail->money = $userdetail->money + $this->_lastMoney;
            } else {
                $userdetail->money = $userdetail->money + $this->getFeeByType(Application_Model_FeeType::EstimateSum);
            }
            $afterMoney = $userdetail->money;
            $userdetail->save();

            $history = new Application_Model_UserAccountHistory();
            $history->type = 1;
            $history->beforeMoney = $beforeMoney;
            $history->afterMoney = $afterMoney;
            $history->comment = '运单：' . $this->_billNo . '退单费';
            $history->dateCreated = date("Y-m-d H:i:s");
            $history->relaseId = $this->_id;
            $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $history->accountId = $this->_userId;
            $history->save();
            Application_Model_Operate::addOperate(0, null, $this->_billNo, "异常运单退件入库并退款", $this->_userId);
            $this->addProblemWay(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_InStore);
            $this->addProblemSchedule("退回的包裹已入仓库并退款了，可以提交国际运单了", Application_Model_ProblemWay::Schedule_InStore);
            return 1;
        } else {
            return 0;
        }
    }

    /* 接收用户ID返回一共消费的money */

    public static function sumLastMoney($userid) {
        $where = array();
        $where['userid = '] = $userid;
        $where[' and status >'] = 0;
        return self::getDao()->sum($where, 'lastMoney');
    }

    public static function countWayBill($userid) {
        $where = array();
        $where['userid = '] = $userid;
        $where[' and status >'] = 0;
        return self::getDao()->count($where);
    }

    public static function wayLastTime($userid) {
        $where = array();
        $where['userid = '] = $userid;
        $where[' and status >'] = 0;
        return self::getDao()->max($where, 'dateCreated');
    }

    /* 返回待拣货的列表数据 */

    public static function toPick() {
        $where = array();
        $where['status !='] = self::STATUS_Launch;
        $where[' and interior = '] = self::Interior_Incoice;
        $where[' and ( problem is null or problem = 2 or problem = '] = 0;
        $where[') and datePaid > '] = "2012-01-01";
        return self::getDao()->queryAll($where);
    }

    /* 返回拣货异常的列表数据 */

    public static function pickError() {
        $where = array();
        $where['status !='] = self::STATUS_Launch;
        $where[' and interior = '] = self::Interior_PickError;
        $where[' and ( problem is null or problem = 2 or problem = '] = 0;
        $where[') and datePaid > '] = "2012-01-01";
        return self::getDao()->queryAll($where);
    }

    public function getPayLink($type) {
        $visitingItem = Application_Model_VisitingServer::getByWayId($this->_id);
    }

    public static function getCountByUserId($userid) {
        return self::getDao()->count(array("userId = " => $userid));
    }

    public static function getOutDelivered() {
        $where[" interior in "] = "(" . self::Interior_OutTransportation . "," . self::Interior_Overachieve . "," . self::Interior_Transportation . ")";
        return self::getDao()->queryAll($where);
    }

    public static function ByMaxId($wayMaxId) {
        $where[" id > "] = $wayMaxId;
        $where[" and status != "] = self::STATUS_Cancel;
        return self::getDao()->queryAll($where);
    }

    public static function MaxId() {
        return self::getDao()->max(array(), "id");
    }

    public function getSplitWeight() {
        return Application_Model_WaySplit::byWayId($this->_id);
    }

    public function affirmtransportation() {
        if ($this->_interior == Application_Model_wayBillItem::Interior_Singleno || $this->_interior == Application_Model_wayBillItem::Interior_OutTransportation) {
            $this->_interior = Application_Model_wayBillItem::Interior_Transportation;
            $this->save();
            $this->addBillLog(Application_Model_wayBillItem::Interior_Transportation, null, "system");
        }
    }

    public static function byAgentNo($agentNo) {
        $where[" agentNo = "] = $agentNo;
        return self::getDao()->queryOne($where);
    }
    
    public static function countWay($waySearch) {
        return Application_Model_wayBillItem::getDao()->count($waySearch->getSearchFileds());
    }

    public function _addFinanceTransaction($account, $beforeMoney, $data) {
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        try {

            $api = new General($beforeMoney, $account);

            $data = array(
                'trader' => 'uuch-backend-account',
                'customer_id' => $data['account_id'],
                'member' => 'admin',
                'amount' => $data['money'],
                'currency' => 'CNY',
                'rate' => '1',
                'rate_amount' => '0',
                'period_start' => $beforeMoney,
                'period_end' => $account->Money,
                'business_type' => 'gjyftk-cr',
                'order_sn' => $data['order_sn']
            );
            $api->setFields($data);
            $api->addTransaction();
        } catch (Exception $ex) {
          //  echo $ex->getMessage();
        }
    }

    protected function _addFinance($account, $data) {
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $api = new General($data['amount'], $account);
        $api->setFields($data);
        $api->addTransaction();
    }

}
